package com.sunyy.codegenerator.controller;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.sunyy.codegenerator.common.Message;
import com.sunyy.codegenerator.common.MyException;
import com.sunyy.codegenerator.dto.templateGroup.PageListTemplateGroupDto;
import com.sunyy.codegenerator.dto.templateGroup.SaveTemplateGroupDto;
import com.sunyy.codegenerator.entity.TemplateGroup;
import com.sunyy.codegenerator.service.TemplateGroupService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 模板分组控制层
 *
 * @author sunyy
 * @since 2025/7/19
 */
@Slf4j
@RestController
@RequestMapping("/templateGroup")
public class TemplateGroupController {

    @Resource
    private TemplateGroupService templateGroupService;

    /**
     * 新增分组内的模板文件
     */
    @PostMapping("/saveTemplateGroup")
    public Message<?> add(@RequestBody SaveTemplateGroupDto dto) {
        templateGroupService.saveTemplateGroup(dto);
        return Message.okWithNothing();
    }

    /**
     * 删除分组内的模板文件
     */
    @PostMapping("/deleteTemplateGroup")
    public Message<?> add(Long id) {
        templateGroupService.deleteTemplateGroup(id);
        return Message.okWithNothing();
    }

    /**
     * 根据groupId查询模板文件列表
     *
     * @param dto
     * @return
     */
    @PostMapping("/pageListTemplateGroup")
    public Page<TemplateGroup> pageListTemplateGroup(@RequestBody PageListTemplateGroupDto dto) {
        if (dto == null) {
            throw new MyException("入参不能为空!!");
        }
        Page<TemplateGroup> page = new Page<>();
        page.setPageNumber(dto.getPageNumber() == null || dto.getPageNumber() < 1 ? 1 : dto.getPageNumber());
        page.setPageSize(dto.getPageSize() == null || dto.getPageSize() < 1 || dto.getPageSize() > 100 ? 10 : dto.getPageSize());
        QueryWrapper wrapper = new QueryWrapper();
        if (dto.getPkid() != null) {
            wrapper.eq("pkid", dto.getPkid());
        }
        if (dto.getGroupName() != null) {
            wrapper.like("group_name", dto.getGroupName());
        }
        if (dto.getGroupDesc() != null) {
            wrapper.like("group_desc", dto.getGroupDesc());
        }
        if (dto.getCreateStartTime() != null) {
            wrapper.ge("create_time", dto.getCreateStartTime());
        }
        if (dto.getCreateEndTime() != null) {
            wrapper.lt("create_time", dto.getCreateEndTime());
        }
        return templateGroupService.page(page, wrapper);
    }

}
